package com.tarena.rocketmq.normal;

import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;

@Slf4j
public class NormalConsumer {
    public static void main(String[] args) {
        //1.创建默认rocketmq消费者
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("normal-group-consume");
        consumer.setNamesrvAddr("localhost:9876");
        //2.订阅主题
        try {
            consumer.subscribe("normal-topic","*");
        }catch (Exception e){
            log.error("订阅主题失败",e);
        }
        //3.绑定监听器
        MessageListenerConcurrently messageListenerConcurrently = new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext context) {
                byte[] body = list.get(0).getBody();
                String msg=new String(body);
                log.info("消费者接收到消息:{}",msg);
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        };
        //4.启动消费者
        try {
            consumer.registerMessageListener(messageListenerConcurrently);
            consumer.start();
        }catch (Exception e){
            log.error("启动消费者失败",e);
        }
    }
}
